package com.xbongbong.saas.model.impl;/*/*/

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessRelatedDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasProcessRelatedDataModel;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.formdata.pojo.SaasSpecialParamPojo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.WorkOrderDao;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderProductEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.product.WorkOrderProductEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderProductModel;
import com.xbongbong.saas.model.WorkOrderSubDataModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 *
 * @author 魏荣杰
 * @date 2019/3/12 9:57
 * @since v1.0
 * @version v1.0
 */
@Service("workOrderModel")
public class WorkOrderModelImpl implements WorkOrderModel {
    private static final Logger LOG = LoggerFactory.getLogger(WorkOrderModelImpl.class);

    @Resource
    private WorkOrderDao workOrderDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private WorkOrderSubDataModel workOrderSubDataModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private PaasProcessRelatedDataModel paasProcessRelatedDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private WorkOrderProductModel workOrderProductModel;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private OutstockModel outstockModel;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WORK_ORDER, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(WorkOrderEntity entity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = workOrderDao.insert(entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        return insert;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WORK_ORDER, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(WorkOrderEntity entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer update = workOrderDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        if (Objects.equals(1, update) || Objects.equals(1, updateSub)) {
            // 更新时间
            update = workOrderDao.updateTime(DateTimeUtil.getInt(), entity.getId(), entity.getCorpid());
            // 更新es
            InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return update;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WORK_ORDER, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatchList(List<WorkOrderEntity> workOrderEntityList, String corpid) throws XbbException {
        StandardizeDataUtil.standardize4EntityList(workOrderEntityList);
        Integer update = workOrderDao.updateBatchList(workOrderEntityList, corpid);
//        LOG.warn("update workorder=  " + JSON.toJSONString(workOrderEntityList));
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (WorkOrderEntity entity : workOrderEntityList) {
            InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
            insertDTO.getSource().remove("creatorId");
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);

        // TODO: 9/21/2020 021
        return update;
    }

    @Override
    public List<WorkOrderEntity> findEntitys(Map<String, Object> param) {
        List<WorkOrderEntity> entitys = workOrderDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return workOrderDao.getEntitysCount(param);
    }

    @Override
    public Integer save(WorkOrderEntity workOrderEntity) throws XbbException {
        if (workOrderEntity.getId() == null || workOrderEntity.getId().equals(0L)) {
            return insert(workOrderEntity);
        }
        return update(workOrderEntity);
    }

    @Override
    public WorkOrderEntity getByKey(Long key, String corpid) {
        WorkOrderEntity workOrderEntity = workOrderDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(workOrderEntity), IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        return workOrderEntity;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WORK_ORDER, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> deleteIdIn, String corpid) throws XbbException {
        Integer integer = workOrderDao.deleteBatch(deleteIdIn, corpid);
        paasEsModel.deleteBatch(deleteIdIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_WORK_ORDER);

        paasFormSubDataModel.deleteBatchByDataId(deleteIdIn, corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WORK_ORDER, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_WORK_ORDER);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        return workOrderDao.deleteByKey(key,corpid);
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WORK_ORDER, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer result = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            result = workOrderDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
        }
        if (!subList.isEmpty()) {
            workOrderSubDataModel.updateBatch(subList, corpid);
        }
        return result;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WORK_ORDER, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer result = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            result = workOrderDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_WORK_ORDER, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            workOrderSubDataModel.updateBatch(subList, corpid);
        }
        return result;
    }

    @Override
    public List<WorkOrderEntity> findNullArrayData(String corpid) {
        List<WorkOrderEntity> entities = workOrderDao.findNullArrayData(corpid);
        paasFormSubDataModel.findSubEntity(corpid, entities, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
        return entities;
    }

    @Override
    public List<WorkOrderEntity> findEntitysWithoutSub(Map<String, Object> param) {
        return workOrderDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO, JSONObject data) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        SaasSpecialParamPojo saasSpecialParamPojo = formatExplainDTO.getSaasSpecialParamPojo();
        boolean fromCopy = Objects.nonNull(saasSpecialParamPojo) && Objects.equals(saasSpecialParamPojo.getFromCopy(), BasicConstant.ONE);
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        boolean unitNoEdit = false;
        if (Objects.nonNull(dataEntity) && !fromCopy) {
            List<OutstockProductEntity> upStreamProduct = outstockProductModel.getUpStreamProduct(corpid, OutstockTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), dataEntity.getId());
            if (upStreamProduct.isEmpty()) {
                //校验审批中是否有下游出库单
                if (commonHelp.isOpenWorkFlow(corpid)) {
                    List<PaasFormDataEntityExt> approvalPaasFormDataList = outstockModel.findOutstockList(corpid, OutstockTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), dataEntity.getId(),
                            Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()), Arrays.asList(FieldTypeEnum.DATAID.getAlias()));
                    if (!approvalPaasFormDataList.isEmpty()) {
                        unitNoEdit = true;
                    }
                } else {
                    List<PaasProcessRelatedDataEntity> paasProcessRelatedDataEntities = paasProcessRelatedDataModel.getByRefIdAndBusinessType(dataEntity.getId(), XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), corpid);
                    if (!paasProcessRelatedDataEntities.isEmpty()) {
                        unitNoEdit = true;
                    }
                }
            }else {
                unitNoEdit = true;
            }
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, WorkOrderEnum.SPARE_PARTS.getAttr())) {
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.WORK_ORDER, corpid, BasicConstant.ONE, unitNoEdit);
                fieldAttrEntity.setSupportScanning(1);
            } else if (Objects.equals(attr, WorkOrderEnum.LINK_CUSTOMER.getAttr()) || Objects.equals(attr, WorkOrderEnum.LINK_OPPORTUNITY.getAttr()) || Objects.equals(attr, WorkOrderEnum.LINK_CONTRACT.getAttr())) {
                if (fromCopy) {
                    continue;
                }
                if (Objects.isNull(data)) {
                    fieldAttrEntity.setEditable(0);
                } else {
                    String string = data.getString(attr);
                    // 这里判断是否等于[] 是因为线上有这种脏数据
                    if (StringUtil.isNotEmpty(string) && !string.equals("[]")) {
                        fieldAttrEntity.setEditable(0);
                    }
                }
            }
        }
    }

    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, WorkOrderEnum.LINK_CUSTOMER.getAttr(), WorkOrderEnum.LINK_CUSTOMER_HIDE.getAttr(), WorkOrderEnum.LINK_CUSTOMER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, WorkOrderEnum.LINK_CONTACT.getAttr(), WorkOrderEnum.LINK_CONTACT_HIDE.getAttr(), WorkOrderEnum.LINK_CONTACT.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, WorkOrderEnum.LINK_OPPORTUNITY.getAttr(), WorkOrderEnum.LINK_OPPORTUNITY_HIDE.getAttr(), WorkOrderEnum.LINK_OPPORTUNITY.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, WorkOrderEnum.LINK_CONTRACT.getAttr(), WorkOrderEnum.LINK_CONTRACT_HIDE.getAttr(), WorkOrderEnum.LINK_CONTRACT.getFieldType());
        // 格式化关联产品,工单的产品在实施备件内显示
//        formatProduct4Show(result, formDataUpdateGetDTO);
    }

    @Override
    public void getProductList(String corpid, List<WorkOrderProductEntity> workOrderProductEntities, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getSaasAttr(), 0D);
                WorkOrderProductEntity productEntity = new WorkOrderProductEntity();
                productEntity.setProductUnit(unit);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setSpecification(specification);
                productEntity.setProductPrice(price);
                productEntity.setSort(sort);
                /*JSONObject jsonObject = new JSONObject();
                jsonObject.put(WorkOrderProductEnum.PRODUCT.getAttr(), pageProductId);
                jsonObject.put(WorkOrderProductEnum.UNIT.getAttr(), unit);
                jsonObject.put(WorkOrderProductEnum.NUM.getAttr(), productNum);
                jsonObject.put(WorkOrderProductEnum.MEMO.getAttr(), "");
                jsonObject.put(WorkOrderProductEnum.PRICE.getAttr(), price);
                productEntity.setData(jsonObject);*/
                workOrderProductEntities.add(productEntity);
            }
        }
    }

    @Override
    public JSONObject formatSingleProduct(WorkOrderProductEntity workOrderProductEntity) {
        JSONObject json = workOrderProductEntity.getData();
        Double rate = showFormatHelp.approvalSetBusinessUnit(json, workOrderProductEntity);
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (WorkOrderProductEnum workOrderProductEnum : WorkOrderProductEnum.values()){
                String attr = workOrderProductEnum.getAttr();
                switch (workOrderProductEnum){
                    case PRODUCT:
                        json.put(attr,workOrderProductEntity.getProductId());
                        break;
                    case NUM:
                        json.put(attr,workOrderProductEntity.getProductNum());
                        break;
                    //case SUBTOTAL:
//                            json.put(attr,workOrderProductEntity.get)
                    //break;
                    case MEMO:
//                            json.put(attr,workOrderProductEntity.getMemo());
                        break;
                    case UNIT:
                        json.put(attr,workOrderProductEntity.getProductUnit());
                        break;
                    case PRICE:
                        json.put(attr, workOrderProductEntity.getProductPrice());
                        break;
                    default:
                        break;
                }
            }
        }
        if (Objects.nonNull(workOrderProductEntity.getProductPriceArr())) {
            json.put(ProductConstant.PRODUCT_PRICE, workOrderProductEntity.getProductPriceArr());
        }
        json.put(WorkOrderProductEnum.OUTSTOCK_NUM.getAttr(), Arith.div(workOrderProductEntity.getOutstockNum(), rate));
        json.put(WorkOrderProductEnum.WAIT_OUTSTOCK_NUM.getAttr(),Arith.div(Arith.sub(workOrderProductEntity.getProductNum(), workOrderProductEntity.getOutstockNum()), rate));
        return json;
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        // 获取关联产品
        List<WorkOrderProductEntity> workOrderProductEntityList = new ArrayList<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(WorkOrderEnum.SPARE_PARTS.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, WorkOrderEnum.SPARE_PARTS.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArr);
                getProductList(corpid, workOrderProductEntityList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(WorkOrderEnum.SPARE_PARTS.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        WorkOrderProductEntity workOrderProductEntity = new WorkOrderProductEntity();
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            workOrderProductEntity.setId(subProductId);
                        }
                        workOrderProductEntity.setProductId(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()));
                        workOrderProductEntity.setData(jsonObject);
                        workOrderProductEntityList.add(workOrderProductEntity);
                    }
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            workOrderProductEntityList = workOrderProductModel.getProductsByWorkOrderId(dataId, corpid, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
        }
        List<Long> productIdList = new ArrayList<>();
        workOrderProductEntityList.forEach(item->{
            productIdList.add(item.getProductId());
        });
        Map<Long, ProductEntityExt> productMap = productModel.getProductMapByIds(corpid, productIdList, DelEnum.NORMAL.getDel(), Arrays.asList(StringConstant.SAAS_LINK_BUSINESS_ID, ProductEnum.getAttrConnectData(ProductEnum.STOCK), ProductEnum.getEsAttr4Keyword(ProductEnum.NAME), ProductEnum.getAttrConnectData(ProductEnum.ONLINE), ProductEnum.getAttrConnectData(ProductEnum.ENABLE_MULTI_UNIT)));
        Set<Long> multiUnitProductIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productMap.forEach((key,value)->{
            if (Objects.equals(value.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1)) {
                multiUnitProductIds.add(key);
            }
        });
        Map<Long, List<MultiUnitPricePoJo>> priceMap = productUnitPriceModel.getPriceMapByProductIdSet(corpid, multiUnitProductIds);
        JSONArray productArray = new JSONArray();
        for (WorkOrderProductEntity workOrderProductEntity : workOrderProductEntityList){
            Long productId = workOrderProductEntity.getProductId();
            if (Objects.isNull(productId) && Objects.nonNull(workOrderProductEntity.getData())) {
                productId = workOrderProductEntity.getData().getLong(SelectProductEnum.PRODUCT.getAttr());
            }
            if (Objects.nonNull(priceMap.get(productId))) {
                workOrderProductEntity.setProductPriceArr(JSONArray.parseArray(JSONArray.toJSONString(priceMap.get(productId))));
            }
//            workOrderProductEntity.setProductPrice(productIdAndPrice.getOrDefault(workOrderProductEntity.getProductId(), 0D));
            JSONObject json = formatSingleProduct(workOrderProductEntity);
            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,workOrderProductEntity.getId());
                if (Objects.isNull(workOrderProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(workOrderProductEntity.getCorpid(),workOrderProductEntity.getProductUnit()));
            }
            json.put("refId",workOrderProductEntity.getId());
            productArray.add(json);
        }
        data.put(WorkOrderEnum.SPARE_PARTS.getAttr(),productArray);
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateTimeUtil.getInt();
        // 更新时间
        Integer success = workOrderDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
        paasEsModel.update(insertDTO);
        return success;
    }
}
